package com.jt.sys.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.druid.util.StringUtils;
import com.jt.common.annotation.RequestLog;
import com.jt.common.exception.ServiceException;
import com.jt.common.vo.PageObject;
import com.jt.sys.dao.SysConfigDao;
import com.jt.sys.entity.SysConfig;
import com.jt.sys.service.SysConfigService;
@Service

@Transactional
public class SysConfigServiceImpl implements SysConfigService {
	@Autowired
	private SysConfigDao sysConfigDao;
	@Override
	@RequestLog("查看配置信息")
	public PageObject<SysConfig> findPageObjects(String name, Integer pageCurrent) {
		/**对参数进行合法性校验*/
		if(pageCurrent==null||pageCurrent<1)
			throw new IllegalArgumentException("当前页码不正确");
		int rowCount = sysConfigDao.getRowCount(name);
		/**查询总条数,判断是否还要返回结果*/
		if(rowCount==0)
			throw new ServiceException("搜索没有记录");
		/**查询当前页数据*/
		int pageSize=6;
		int startIndex=(pageCurrent-1)*pageSize;
		List<SysConfig> records = sysConfigDao.findPageObjects(name, startIndex, pageSize);
		/**封装数据(PageObject)*/
		PageObject<SysConfig> pageObject = new PageObject<>();
		pageObject.setPageCurrent(pageCurrent);
		pageObject.setPageSize(pageSize);
		pageObject.setRecords(records);
		pageObject.setRowCount(rowCount);
		/**返回数据*/
		return pageObject;
	}
	@Override
	@RequestLog("删除配置信息")
	public int deleteObjects(Integer... ids) {
		//1.对参数进行合法验证
		if(ids==null||ids.length==0)
			throw new IllegalArgumentException("未选中删除元素,请重新选择");
		//2.执行删除操作
		int rows = 0;
		try{
			rows = sysConfigDao.deleteObjectById(ids);
		}catch(Throwable e){
			e.printStackTrace();//输出到日志文件
			//给运维人员疯狂打call
			throw new ServiceException("系统维护中...请耐心等待...正在给运维人员疯狂打call!");
		}
		//3.判定删除结果
		if(rows==0)
			throw new ServiceException("记录可能已经不存在了");
		//4.返回数据
		return rows;
	}
	@Override
	@RequestLog("保存配置信息")
	public int saveObject(SysConfig entity) {
		//1.合法校验
		if(entity==null)
			throw new IllegalArgumentException("保存对象不能为空");
		if(StringUtils.isEmpty(entity.getName()))
			  throw new IllegalArgumentException("参数名不能为空");
		if(StringUtils.isEmpty(entity.getValue()))
			  throw new IllegalArgumentException("参数值不能为空");
		int rows = sysConfigDao.insertObject(entity);
		if(rows!=1)
			throw new IllegalArgumentException("写入失败");
		return rows;
	}
	@Override
	@RequestLog("更新配置信息")
	public int updateObject(SysConfig entity) {
		if(entity==null)
			  throw new IllegalArgumentException("对象不能为空");
		if(StringUtils.isEmpty(entity.getName()))
			  throw new IllegalArgumentException("参数名不能为空");
		if(StringUtils.isEmpty(entity.getValue()))
			  throw new IllegalArgumentException("参数值不能为空");
		int rows = sysConfigDao.updateObject(entity);
		if(rows==0)
			throw new ServiceException("该记录可能不存在");
		return rows;
		
	}

}
